package com.farmer.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.farmer.mapper.PolicyMapper;
import com.farmer.mapper.UserMapper;
import com.farmer.pojo.Comment;

import com.farmer.pojo.Policy;
import com.farmer.pojo.User;
import com.farmer.service.CommentService;
import com.farmer.mapper.CommentMapper;
import com.farmer.utils.JwtHelper;
import com.farmer.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86183
* @description 针对表【comment(评论信息表)】的数据库操作Service实现
* @createDate 2024-05-03 16:00:28
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PolicyMapper policyMapper;

    @Override
    public Result add(String token, Comment comment) {
        int userid = jwtHelper.getUserId(token).intValue();
        User user = userMapper.selectById(userid);
        comment.setUserId(userid);
        comment.setUserName(user.getName());
        System.out.println(user.getAvatar());
        comment.setAvatar(user.getAvatar());
      comment.setTime(DateFormat.getDateInstance().format(new Date()));
        Policy policy = policyMapper.selectById(comment.getPolicyId());
        if (policy != null) {
            comment.setPolicyTitle(policy.getName());
        }else{
            comment.setPolicyTitle("未知政策");
        }
        commentMapper.insert(comment);
        return Result.ok(null);
    }

    @Override
    public Result delete(Integer id) {
        commentMapper.deleteById(id);
        return null;
    }
    @Override
    public Result deleteBatch(List<Integer> ids){
        for(Integer id:ids){
            commentMapper.deleteById(id);
        }
        return Result.ok(null);
    }

    @Override
    public Result update(Comment comment) {
        commentMapper.updateById(comment);
        return Result.ok(null);
    }


    @Override
    public Result getById(Integer id) {
       Comment comment = commentMapper.selectById(id);
        if (comment!=null) {
            return Result.build(comment, 111, "查询成功");
        }else{
            return Result.build(null,101,"查询失败");
        }
    }

    @Override
    public Result getAll() {
        List<Comment> comments=commentMapper.selectList(null);
        if (comments!=null&&!comments.isEmpty()) {
            return Result.build(comments, 111, "查询成功");
        }else{
            return Result.build(null,101,"查询失败");
        }
    }

//    @Override
//    public Result getByPolicyId(Integer id){
//        Comment comment = new Comment();
//        comment.setPolicyId(id);
//        comment.setParentId(0);
//       List<Comment> comments1 = commentMapper.selectList(null);
//       for (Comment dbComment:comments1){
//           comment.setParentId(dbComment.getId());
//           List<Comment> children = commentMapper.selectList(null);
//           dbComment.setChildren(children);
//       }
//     return Result.ok(comments1);
//   }

    @Override
    public List<Comment> listTree(){
        List<Comment> list = this.list();
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int index=0;index<list.size();index++){
            map.put(list.get(index).getId(),index);
        }
//        遍历寻找父节点
        for(Comment comment:list){
            Integer pid = comment.getParentId();
//            有父节点（是子节点）
            if(pid!=0){
//                获取·父节点
                Integer indexFather = map.get(pid);
                Comment father = list.get(indexFather);
                if(father.getChildren()==null){
                    father.setChildren(new ArrayList<>());
                }
//                在父节点上添加此节点
                father.getChildren().add(comment);
            }
        }
//        过滤出一级节点
        List<Comment> ans=list.stream().filter(child->child.getParentId()==0).collect(Collectors.toList());
//        return Result.ok(ans);
        return ans;
    }


    /*
     * 分页查询*/
    @Override
    public Result page(Integer pageNum, Integer pageSize){
        // 创建分页构造对象
        Page<Comment> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        IPage<Comment> result = commentMapper.selectPage(page, null);
        // 封装到统一响应体Result中
        return Result.ok(result);
    }

    @Override
    public Result getByTitleLike(String content) {
        // 构造查询条件
        LambdaQueryWrapper<Comment> lambdaqueryWrapper = new LambdaQueryWrapper<>();
        lambdaqueryWrapper.like(Comment::getContent, content); // 根据标题模糊查询
        // 执行查询
        List<Comment> comments= commentMapper.selectList(lambdaqueryWrapper);
        // 返回结果
        if (comments != null && !comments.isEmpty()) {
            return Result.build(comments, 111, "查询成功");
        } else {
            return Result.build(null, 101, "未找到匹配的信息");
        }
    }

}




